package typejump.gui;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.Hashtable;

import javax.swing.Box;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class ObjectPanel extends JPanel {
	private PropertyMediator mediator;
	private JTextField idField;
	private JPanel propBox;
	
	private Hashtable<String, JTextField> textFields;
	
	public ObjectPanel() {
		textFields = new Hashtable<String, JTextField>();
		
		idField = new JTextField(10);
		
		Box idBox = Box.createHorizontalBox();
		idBox.add(new JLabel("id "));
		idBox.add(idField);
		
		JPanel mainBox = new JPanel();
		mainBox.setLayout(new GridBagLayout());
		
		GridBagConstraints gc = new GridBagConstraints();
		gc.gridx = 0;
		gc.gridy = 0;
		gc.gridwidth = 1;
		gc.gridheight = 1;
		gc.anchor = GridBagConstraints.WEST;
		
		mainBox.add(idBox, gc);
		gc.gridy++;
		
		mainBox.add(new JLabel("Parameters"), gc);
		gc.gridy++;
		
		propBox = new JPanel();
		propBox.setLayout(new GridBagLayout());
		
		
		add(mainBox);
	}
	
	public void commitValues() {
		if (mediator == null) return;
		String[] names = mediator.getPropertyNames();
		for (String name : names) {
			mediator.setProperty(name, textFields.get(name).getText());
		}
	}
	
	public void updateValues() {
		if (mediator == null) return;
		String[] names = mediator.getPropertyNames();
		for (String name : names) {
			textFields.get(name).setText(mediator.getProperty(name));
		}
	}
	
	public void setMediator(PropertyMediator mediator) {
		if (this.mediator == mediator) return;

		propBox.removeAll();
		textFields.clear();
		GridBagConstraints gc = new GridBagConstraints();
		gc.gridx = 0;
		gc.gridy = 0;
		gc.gridwidth = 1;
		gc.gridheight = 1;
		
		String[] names = mediator.getPropertyNames();
		for (String name : names) {
			gc.gridx = 0;
			propBox.add(new JLabel(name), gc);
			
			JTextField field = new JTextField(10);
			field.setText(mediator.getProperty(name));
			textFields.put(name, field);
			
			gc.gridx = 1;
			propBox.add(field, gc);
			
			gc.gridy++;
		}
		
		propBox.invalidate();
		invalidate();
		validate();
		doLayout();
	}
}
